<template>
  <div id="app" class="min-h-screen theme-transition" :class="themeState.currentTheme === 'light' ? 'theme-light' : 'theme-dark'">
    <!-- 全屏页面（无侧边栏） -->
    <template v-if="isFullscreenPage">
      <router-view />
    </template>
    
    <!-- 常规页面（带侧边栏） -->
    <template v-else>
      <!-- 主要布局 -->
      <div class="flex h-screen">
        <!-- 侧边栏 -->
        <Sidebar />
        
        <!-- 主内容区域 -->
        <div class="flex-1 flex flex-col overflow-hidden">
          <!-- 顶部导航栏 -->
          <header class="h-16 backdrop-blur-sm border-b flex items-center justify-between px-6 relative z-10 flex-shrink-0"
                  :class="themeState.isLight ? 'bg-white/80 border-gray-200' : 'bg-gray-800/50 border-blue-500/20'">
          <div class="flex items-center space-x-4">
          </div>
          
          <!-- 右侧工具栏 -->
          <div class="flex items-center space-x-4 relative z-50">
            <!-- 翻译状态指示器 -->
            <div v-if="isTranslating" class="flex items-center space-x-2" :class="themeState.isLight ? 'text-blue-600' : 'text-blue-400'">
              <div class="w-4 h-4 border-2 border-t-transparent rounded-full animate-spin" :class="themeState.isLight ? 'border-blue-600' : 'border-blue-400'"></div>
              <span class="text-sm">{{ ts('翻译中...') }}</span>
            </div>
            
          <!-- 主题选择器 -->
          <ThemeSelector @theme-changed="onThemeChanged" />
            
            <!-- 语言选择器 -->
            <div class="relative language-selector-container">
              <button
                @click="showLanguageMenu = !showLanguageMenu"
                @click.stop
                class="flex items-center space-x-2 px-3 py-2 rounded-lg transition-colors border"
                :class="themeState.isLight ? 'bg-gray-100 hover:bg-gray-200 border-gray-300' : 'bg-white/10 hover:bg-white/20 border-white/20'"
                type="button"
              >
                <span class="text-xl">{{ currentLanguageFlag }}</span>
                <span class="text-sm" :class="themeState.isLight ? 'text-gray-900' : 'text-white'">{{ currentLanguageName }}</span>
                <ChevronDown class="w-4 h-4 transition-transform" :class="[themeState.isLight ? 'text-gray-900' : 'text-white', { 'rotate-180': showLanguageMenu }]" />
              </button>
              
              <!-- 语言菜单 -->
              <div 
                v-if="showLanguageMenu"
                class="absolute right-0 top-full mt-2 rounded-lg shadow-2xl min-w-[150px] overflow-hidden"
                :class="themeState.isLight ? 'bg-white border border-gray-200' : 'bg-gray-900 border border-gray-600'"
                style="z-index: 10000;"
              >
                <div
                  v-for="lang in languages"
                  :key="lang.code"
                  @click="selectLanguage(lang.code)"
                  @click.stop
                  class="flex items-center space-x-3 px-4 py-3 cursor-pointer transition-colors"
                  :class="[
                    currentLanguage === lang.code 
                      ? (themeState.isLight ? 'bg-blue-50 text-blue-700' : 'bg-blue-500/20 text-blue-400')
                      : (themeState.isLight ? 'text-gray-700 hover:bg-gray-100' : 'text-white hover:bg-white/10')
                  ]"
                >
                  <span class="text-xl">{{ lang.flag }}</span>
                  <span class="text-sm">{{ lang.name }}</span>
                  <Check v-if="currentLanguage === lang.code" class="w-4 h-4 ml-auto" 
                         :class="themeState.isLight ? 'text-blue-600' : 'text-blue-400'" />
                </div>
              </div>
            </div>
            
            
            <!-- 用户信息 -->
            <div class="flex items-center space-x-3">
              <div class="text-right">
                <div class="text-sm font-medium" :class="themeState.isLight ? 'text-gray-900' : 'text-white'">{{ ts('欢迎回来') }}</div>
                <div class="text-xs" :class="themeState.isLight ? 'text-blue-600' : 'text-blue-400'">{{ ts('今天是美好的一天，让我们开始工作吧！') }}</div>
              </div>
              <div class="w-8 h-8 bg-blue-500 rounded-full flex items-center justify-center">
                <User class="w-4 h-4 text-white" />
              </div>
            </div>
          </div>
        </header>
        
          <!-- 主要内容 -->
          <main class="flex-1 overflow-auto">
            <keep-alive include="PolicyQuery">
              <router-view />
            </keep-alive>
          </main>
        </div>
      </div>
    </template>
    
    <!-- 政策通知中心 -->
    <PolicyNotificationCenter />
    
    <!-- 翻译设置面板 -->
    <div 
      v-if="showTranslationSettings"
      class="fixed inset-0 bg-black/50 flex items-center justify-center z-[9000]"
      @click="showTranslationSettings = false"
    >
      <div 
        class="bg-gray-800 rounded-lg p-6 max-w-md w-full mx-4 border border-gray-600"
        @click.stop
      >
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-xl font-semibold text-white">{{ ts('翻译设置') }}</h3>
          <button 
            @click="showTranslationSettings = false"
            class="text-gray-400 hover:text-white"
          >
            <X class="w-5 h-5" />
          </button>
        </div>
        
        <div class="space-y-3">
          <label class="flex items-center space-x-2">
            <input
              type="checkbox"
              v-model="globalState.autoTranslateEnabled"
              @change="toggleAutoTranslate"
              class="rounded"
            >
            <span class="text-white text-sm">{{ ts('启用自动翻译') }}</span>
          </label>
          
          <div class="text-xs text-gray-300">
            <div>{{ ts('缓存统计') }}: {{ ts('已缓存') }} {{ translationService.getStats().cacheSize }} {{ ts('条翻译') }}</div>
            <div>{{ ts('当前提供商') }}: {{ getProviderName(translationService.getStats().currentProvider) }}</div>
            <div v-if="translationService.getStats().currentProvider === 'baidu'" class="text-yellow-400 mt-2">
              ⚠️ {{ ts('百度翻译API可能因CORS限制无法使用') }}
            </div>
            <div v-else-if="translationService.getStats().currentProvider === 'free'" class="text-green-400 mt-2">
              ✅ {{ ts('使用免费翻译服务（推荐）') }}
            </div>
          </div>
          
          <div class="flex space-x-2">
            <button
              @click="switchTranslationProvider('free')"
              class="px-3 py-1 bg-green-500/20 text-green-400 rounded text-xs hover:bg-green-500/30 transition-colors"
              :class="{ 'bg-green-500/40': translationService.getStats().currentProvider === 'free' }"
            >
              {{ ts('免费服务') }}
            </button>
            <button
              @click="switchTranslationProvider('google')"
              class="px-3 py-1 bg-blue-500/20 text-blue-400 rounded text-xs hover:bg-blue-500/30 transition-colors"
              :class="{ 'bg-blue-500/40': translationService.getStats().currentProvider === 'google' }"
            >
              {{ ts('Google') }}
            </button>
            <button
              @click="switchTranslationProvider('baidu')"
              class="px-3 py-1 bg-yellow-500/20 text-yellow-400 rounded text-xs hover:bg-yellow-500/30 transition-colors"
              :class="{ 'bg-yellow-500/40': translationService.getStats().currentProvider === 'baidu' }"
            >
              {{ ts('百度') }}
            </button>
          </div>
          
          <div class="flex space-x-2 mt-3">
            <button
              @click="clearTranslationCache"
              class="px-3 py-1 bg-red-500/20 text-red-400 rounded text-xs hover:bg-red-500/30 transition-colors"
            >
              {{ ts('清除缓存') }}
            </button>
            <button
              @click="runPreTranslation"
              class="px-3 py-1 bg-blue-500/20 text-blue-400 rounded text-xs hover:bg-blue-500/30 transition-colors"
            >
              {{ ts('预翻译常用词') }}
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 翻译状态指示器 -->
    <div 
      v-if="isTranslating"
      class="fixed bottom-4 left-4 bg-electric-500/90 text-white px-4 py-2 rounded-lg shadow-lg z-[9500] animate-pulse"
    >
      <div class="flex items-center space-x-2">
        <div class="w-4 h-4 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
        <span>{{ ts('翻译中...') }}</span>
      </div>
    </div>
    
    <!-- Stagewise 工具栏 (仅在开发模式下显示) -->
    <StagewiseToolbar v-if="isDevelopment" :config="stagewiseConfig" />
  </div>
</template>

<script>
import { provide, reactive, computed, watch, nextTick } from 'vue'
import { ChevronDown, User, Settings, X, Check } from 'lucide-vue-next'
import Sidebar from './components/Sidebar.vue'
import ThemeSelector from './components/ThemeSelector.vue'
import { useTranslation } from './composables/useTranslation.js'
import translationService from './services/translationService.js'
import themeService, { themeState } from './services/themeService.js'
import PolicyNotificationCenter from './components/PolicyNotificationCenter.vue'
import { StagewiseToolbar } from '@stagewise/toolbar-vue'
import VuePlugin from '@stagewise-plugins/vue'

export default {
  name: 'App',
  components: {
    Sidebar,
    ThemeSelector,
    ChevronDown,
    User,
    Settings,
    X,
    Check,
    PolicyNotificationCenter,
    StagewiseToolbar
  },
  setup() {
    // 全局状态
    const globalState = reactive({
      currentLanguage: 'zh',
      autoTranslateEnabled: true,
      isTranslating: false
    })

    // 使用翻译系统
    const { ts, isTranslating, autoTranslateEnabled, preTranslate } = useTranslation()

    // 提供全局状态给子组件
    provide('globalState', globalState)

    // 监听语言变化，触发全页面翻译
    watch(() => globalState.currentLanguage, async (newLang, oldLang) => {
      if (newLang !== oldLang && globalState.autoTranslateEnabled) {
        console.log(`语言切换: ${oldLang} -> ${newLang}`)
        globalState.isTranslating = true
        
        try {
          // 等待DOM更新
          await nextTick()
          
          // 预翻译常用词汇
          await preTranslateCommonWords()
          
          // 翻译页面所有文本内容
          await translateAllPageContent()
          
        } catch (error) {
          console.error('翻译失败:', error)
        } finally {
          // 延迟隐藏翻译状态
          setTimeout(() => {
            globalState.isTranslating = false
          }, 1000)
        }
      }
    })

    // 预翻译常用词汇
    const preTranslateCommonWords = async () => {
      const commonWords = [
        '跨境政策咨询平台', '全球政策概览', '智能咨询', '政策查询', '政策分析', 
        '政策匹配', '跨境对比', '政策推送', '定时提醒', '个人中心',
        '欢迎回来', '今天是美好的一天，让我们开始工作吧！', '全国政策分布热力图',
        '正在加载地图数据...', '政策数量', '最新政策', '更新时间', '暂无数据',
        '高', '低', '翻译中...', '翻译设置', '启用自动翻译', '缓存统计',
        '已缓存', '条翻译', '清除缓存', '预翻译常用词', '当前提供商',
        '智能政策分析与决策支持系统', '版权所有·保留一切权利',
        // AI聊天相关
        '您好！我是您的专属政策咨询助手', '请问有什么可以帮助您的吗？',
        '正在思考中...', '发送', '清空对话', '请输入您的问题...',
        '政策解读', '申请指导', '风险评估', '合规建议',
        // 仪表板相关
        '政策总数', '今日更新', '关注地区', '我的收藏',
        '最新政策动态', '热门政策推荐', '个人收藏夹', '系统通知',
        '查看详情', '收藏', '分享', '下载', '打印',
        // 通用词汇
        '加载中...', '搜索', '筛选', '排序', '导出', '导入',
        '确认', '取消', '保存', '删除', '编辑', '添加',
        '成功', '失败', '警告', '信息', '错误',
        '年', '月', '日', '时', '分', '秒',
        '上一页', '下一页', '首页', '末页'
      ]
      
      if (globalState.currentLanguage === 'zh') return
      
      console.log(`开始预翻译 ${commonWords.length} 个常用词汇到 ${globalState.currentLanguage}`)
      
      try {
        await preTranslate(commonWords, globalState.currentLanguage)
        console.log('预翻译完成')
      } catch (error) {
        console.error('预翻译失败:', error)
      }
    }

    // 翻译页面所有文本内容
    const translateAllPageContent = async () => {
      if (globalState.currentLanguage === 'zh') return

      console.log('开始翻译页面所有内容...')
      
      // 获取所有文本节点
      const textNodes = []
      const walker = document.createTreeWalker(
        document.body,
        NodeFilter.SHOW_TEXT,
        {
          acceptNode: function(node) {
            // 过滤掉空白节点和脚本节点
            if (node.nodeValue.trim() === '' || 
                node.parentNode.tagName === 'SCRIPT' || 
                node.parentNode.tagName === 'STYLE') {
              return NodeFilter.FILTER_REJECT
            }
            return NodeFilter.FILTER_ACCEPT
          }
        }
      )

      let node
      while (node = walker.nextNode()) {
        textNodes.push(node)
      }

      console.log(`找到 ${textNodes.length} 个文本节点`)

      // 批量翻译文本节点
      const promises = textNodes.map(async (node) => {
        const originalText = node.nodeValue.trim()
        if (originalText && originalText.length > 0) {
          try {
            const translated = await translationService.translate(originalText, globalState.currentLanguage)
            if (translated !== originalText) {
              node.nodeValue = translated
            }
          } catch (error) {
            console.error('翻译文本节点失败:', originalText, error)
          }
        }
      })

      await Promise.all(promises)
      console.log('页面内容翻译完成')
    }

    // 主题变化处理
    const onThemeChanged = (themeData) => {
      console.log('主题已变更:', themeData)
      // 可以在这里添加主题变化后的特殊处理逻辑
    }

    return {
      globalState,
      themeState,
      ts,
      isTranslating: computed(() => globalState.isTranslating || isTranslating.value),
      autoTranslateEnabled: computed(() => globalState.autoTranslateEnabled),
      preTranslateCommonWords,
      translateAllPageContent,
      onThemeChanged
    }
  },
  data() {
    return {
      showLanguageMenu: false,
      showTranslationSettings: false,
      
      languages: [
        { code: 'zh', name: '中文', flag: '🇨🇳' },
        { code: 'en', name: 'English', flag: '🇺🇸' },
        { code: 'pt', name: 'Português', flag: '🇵🇹' }
      ],
      
      // Stagewise 配置
      stagewiseConfig: {
        plugins: [VuePlugin]
      }
    }
  },
  computed: {
    currentLanguage() {
      return this.globalState.currentLanguage
    },
    
    currentLanguageFlag() {
      const lang = this.languages.find(l => l.code === this.currentLanguage)
      return lang ? lang.flag : '🌐'
    },
    
    currentLanguageName() {
      const lang = this.languages.find(l => l.code === this.currentLanguage)
      return lang ? lang.name : 'Unknown'
    },
    
    cacheSize() {
      return translationService.getStats().cacheSize
    },
    
    currentProvider() {
      return translationService.getStats().currentProvider
    },
    
    // 判断是否为全屏页面（无侧边栏）
    isFullscreenPage() {
      const fullscreenRoutes = ['/', '/welcome']
      return fullscreenRoutes.includes(this.$route.path)
    },
    
    // 判断是否为开发模式
    isDevelopment() {
      return import.meta.env.DEV
    }
  },
  methods: {
    selectLanguage(langCode) {
      console.log('=== 语言选择开始 ===')
      console.log('选择语言:', langCode)
      console.log('当前语言:', this.currentLanguage)
      console.log('菜单状态:', this.showLanguageMenu)
      
      // 关闭菜单
      this.showLanguageMenu = false
      console.log('菜单已关闭')
      
      if (langCode === this.currentLanguage) {
        console.log('语言相同，无需切换')
        return
      }
      
      // 显示翻译状态
      this.globalState.isTranslating = true
      console.log('开始翻译状态')
      
      // 更新语言
      this.globalState.currentLanguage = langCode
      console.log('语言状态已更新')
      
      // 保存到localStorage
      try {
        localStorage.setItem('currentLanguage', langCode)
        console.log('语言设置已保存到localStorage:', langCode)
      } catch (error) {
        console.error('保存语言设置失败:', error)
      }
      
      // 触发翻译事件
      window.dispatchEvent(new CustomEvent('languageChange', {
        detail: { language: langCode }
      }))
      console.log('翻译事件已触发')
      
      console.log('语言已切换到:', langCode)
      
      // 2秒后隐藏翻译状态
      setTimeout(() => {
        this.globalState.isTranslating = false
        console.log('翻译状态已隐藏')
      }, 2000)
      
      console.log('=== 语言选择完成 ===')
    },
    
    toggleAutoTranslate() {
      this.globalState.autoTranslateEnabled = !this.globalState.autoTranslateEnabled
    },
    
    clearTranslationCache() {
      translationService.clearCache()
    },
    
    async runPreTranslation() {
      await this.preTranslateCommonWords()
    },
    
    getProviderName(provider) {
      const providers = {
        'baidu': '百度',
        'google': 'Google',
        'free': '免费服务'
      }
      return providers[provider] || 'Unknown'
    },
    
    switchTranslationProvider(provider) {
      translationService.switchProvider(provider)
    }
  },
  
  mounted() {
    console.log('App组件已挂载')
    console.log('当前语言:', this.currentLanguage)
    console.log('语言选择器状态:', this.showLanguageMenu)
    
    // 确保初始状态正确
    this.showLanguageMenu = false
    
    // 强制重置为中文（用户反馈默认应该是中文）
    console.log('强制设置语言为中文')
    this.globalState.currentLanguage = 'zh'
    
    // 初始化主题系统
    console.log('初始化主题系统')
    console.log('当前主题:', themeState.currentTheme)
    console.log('主题配置:', themeState.theme.name)
    
    // 清除可能的错误语言设置并保存中文
    try {
      localStorage.setItem('currentLanguage', 'zh')
      console.log('语言设置已重置为中文')
    } catch (error) {
      console.error('保存语言设置失败:', error)
    }
    
    // 如果用户之前有保存的语言偏好，可以通过语言选择器重新选择
    // 注释掉原来的自动读取逻辑，确保默认总是中文
    /*
    try {
      const savedLanguage = localStorage.getItem('currentLanguage')
      console.log('从localStorage读取语言设置:', savedLanguage)
      
      if (savedLanguage && savedLanguage !== this.currentLanguage) {
        console.log('应用保存的语言设置:', savedLanguage)
        this.globalState.currentLanguage = savedLanguage
      } else if (!savedLanguage) {
        // 如果没有保存的语言设置，确保设置为中文并保存
        console.log('没有保存的语言设置，设置为中文')
        this.globalState.currentLanguage = 'zh'
        localStorage.setItem('currentLanguage', 'zh')
      }
    } catch (error) {
      console.error('读取语言设置失败:', error)
      this.globalState.currentLanguage = 'zh'
    }
    */
    
    console.log('最终语言设置:', this.currentLanguage)
    
    // 添加全局点击事件监听器
    document.addEventListener('click', (event) => {
      // 如果点击的不是语言选择器区域，关闭菜单
      const languageSelector = event.target.closest('.language-selector-container')
      if (!languageSelector && this.showLanguageMenu) {
        this.showLanguageMenu = false
      }
    })
  }
}
</script>

<style scoped>
/*
Z-INDEX HIERARCHY (弹窗层级规范):
- 基础界面: 1-99
- 导航层级: 100-999 (header: z-10, toolbar: z-50)
- 模态框层级: 9000-9999 (翻译设置: z-9000, 状态指示器: z-9500)
- 顶层弹窗: 10000+ (语言菜单: z-10000, 侧边栏子菜单: z-10001, PolicyWindow: z-10002)
*/

/* 确保页面可以正常滚动 */
#app {
  background: var(--gradient-primary);
  min-height: 100vh;
  transition: background 0.3s ease;
}

/* 修复可能的布局问题 */
.flex-1 {
  flex: 1;
  min-height: 0;
}

/* 确保主内容区域可以滚动 */
main {
  height: calc(100vh - 4rem); /* 减去header高度 */
  overflow-y: auto;
  overflow-x: hidden;
}

.theme-selector {
  height: 40px; /* 缩小高度 */
  padding: 0 12px; /* 缩小内边距 */
  display: flex;
  align-items: center;
  justify-content: center;
}

.language-selector-container button {
  height: 36px; /* 缩小语言切换按钮高度 */
  padding: 0 12px; /* 缩小内边距 */
  font-size: 0.875rem; /* 调整字体大小 */
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 语言选择器样式 */
.language-selector {
  position: relative;
}

.language-menu {
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.5);
  backdrop-filter: blur(10px);
}

.language-menu button {
  transition: all 0.2s ease;
}

.language-menu button:hover {
  background: rgba(255, 255, 255, 0.1) !important;
}

.language-menu button:first-child {
  border-radius: 0.5rem 0.5rem 0 0;
}

.language-menu button:last-child {
  border-radius: 0 0 0.5rem 0.5rem;
}

/* 确保下拉箭头动画 */
.rotate-180 {
  transform: rotate(180deg);
  transition: transform 0.2s ease;
}
</style> 